package com.company;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by lanouhn on 17/7/18.
 */
public class image {
    public static void main(String[] args){
        HttpURLConnection connection = null;
        InputStream is = null;
        String myurl = "http://www.eoeandroid.com/data/attachment/forum/201107/18/142935bbi8d3zpf3d0dd7z.jpg";
        try {
            //图片是二进制数据，将二进制数据转换为图片
            URL url = new URL(myurl);
            connection = (HttpURLConnection)url.openConnection();
            //网络响应码
            int code = connection.getResponseCode();
            if (code==200){
                is = connection.getInputStream();
                byte[] getData = readInputStream(is);
                //存储
                String path = "/Users/lanouhn/Desktop/result.jpg";
                //make new file
                File flie = new File(path);


                FileOutputStream fos = new FileOutputStream(flie);
                fos.write(getData);
                fos.close();

                System.out.println(" read picture success");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static byte[] readInputStream(InputStream is) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = is.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }

        bos.close();
        return bos.toByteArray();
    }

}
